package manager;

import Database.Connectmysql;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ResetPassword extends javax.swing.JFrame {
    private JPasswordField oldPassword,newPassword;
    private JButton confirm;
    private JLabel oldPasswordLabel,newPasswordLabel;
    public ResetPassword(String managerName) {
        setTitle("密码修改");
        setBounds(300, 100, 500, 400);
        setLayout(null);

        oldPassword = new JPasswordField(30);
        newPassword = new JPasswordField(30);
        confirm = new JButton("确认");
        oldPasswordLabel = new JLabel("旧密码");
        newPasswordLabel = new JLabel("新密码");
        oldPassword.setBounds(200, 50, 200, 30);
        newPassword.setBounds(200, 150, 200, 30);
        confirm.setBounds(220, 250, 60, 30);
        oldPasswordLabel.setBounds(100, 50, 100, 30);
        newPasswordLabel.setBounds(100, 150, 100, 30);
        add(newPasswordLabel);
        add(newPassword);
        add(oldPassword);
        add(oldPasswordLabel);
        add(confirm);

        confirm.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               String oldPasswordString = new String(oldPassword.getPassword());
               String newPasswordString = new String(newPassword.getPassword());


               Connectmysql cmysql = new Connectmysql(
                       "jdbc:mysql://localhost:3306/bookmanagement",
                       "root",
                       "root",
                       "com.mysql.cj.jdbc.Driver");
               try {
                   if(cmysql.open()){

                       ResultSet rst= cmysql.executeSql(
                               "select managerpassword from manager where managername=?",
                               new Object[]{managerName}
                       );
                       if(rst.next()&&rst.getString(1).equals(oldPasswordString)){
                           cmysql.executeSqlUpdate("update manager set managerpassword = ? where managername = ?",new Object[]{newPasswordString,managerName});
                           System.out.println("修改成功！");
                           setVisible(false);
                       }else{
                           System.err.println("旧密码输入错误");
                       }
                       rst.close();
                   }
               } catch (ClassNotFoundException f) {
                   f.printStackTrace();
               } catch (SQLException throwables) {
                   throwables.printStackTrace();
               }
           }
        });

        setVisible(true);
    }

    public static void main(String[] args) {
        new ResetPassword("root");
    }
}
